package com.cloud.class05.test;

import java.util.concurrent.Semaphore;

//10个人买个早餐，5个窗口
public class BaoziShop {
    private static final int NUM_WINDOWS = 5;//窗口数
    private static final int NUM_PEOPLE = 10;//购买人数
    //信号量，初始化值为窗口数量
    private Semaphore semaphore = new Semaphore(NUM_WINDOWS);

    public void buyBaozi() {
        try {
            //获取信号量，如果信号量不足，则阻塞等待
            semaphore.acquire();
            System.out.println(Thread.currentThread().getName() + ": 开始买早餐");
            Thread.sleep(1000);
            System.out.println(Thread.currentThread().getName() + ": 结束买早餐");
            //释放信号量，允许下一个线程获取信号量
            semaphore.release();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        BaoziShop baoziShop = new BaoziShop();
        for (int i = 0; i < NUM_PEOPLE; i++) {
            new Thread(() -> {
                baoziShop.buyBaozi();
            }, "Thread-" + i).start();
        }
    }



}

